package com.corpgovernment.common.aspect;

import com.corpgovernment.common.holder.TraceIdHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zl.cui
 * @date 2023/11/20
 */
@Component
@Slf4j
@Order(Integer.MAX_VALUE - 1)
public class CarryQueryParamAdapter implements HandlerInterceptor {

    private static final String RESPONSE_HEADER_QUERY_TRACE_ID_PREFIX = "query-trace-id";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取所有Cookie
        Cookie[] cookies = request.getCookies();
        String paramValue = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(RESPONSE_HEADER_QUERY_TRACE_ID_PREFIX)) { // 判断是否为需要获取的Cookie
                    paramValue = cookie.getValue(); // 获取Cookie中的参数值
                    TraceIdHolder.setTraceId(paramValue);
                    break;
                }
            }
        }
        return true;
    }

}
